package com.wxwx.flutter_alibc;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.alibclogin.AlibcLogin;
import com.alibaba.alibcprotocol.callback.AlibcLoginCallback;
import com.alibaba.alibcprotocol.param.AlibcBizParams;
import com.alibaba.alibcprotocol.param.AlibcDegradeType;
import com.alibaba.alibcprotocol.param.AlibcShowParams;
import com.alibaba.alibcprotocol.param.AlibcTaokeParams;
import com.alibaba.alibcprotocol.param.OpenType;
import com.alibaba.ariver.kernel.common.utils.JSONUtils;
import com.alibaba.baichuan.trade.common.AlibcTradeCommon;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baichuan.nb_trade.AlibcTrade;
import com.baichuan.nb_trade.callback.AlibcTradeCallback;
import com.baichuan.nb_trade.callback.AlibcTradeInitCallback;
import com.baichuan.nb_trade.core.AlibcTradeBiz;
import com.baichuan.nb_trade.core.AlibcTradeSDK;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * FlutterTopPlugin
 * 阿里百川插件
 */
public class FlutterAlibcPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {

    private MethodChannel channel;

    private Application mAppContext;

    private Activity mActivity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_alibc_customer");
        channel.setMethodCallHandler(this);
        mAppContext = (Application) flutterPluginBinding.getApplicationContext();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("initialSDK")) {
            initialSDK(call, result);
        } else if (call.method.equals("authLogin")) {
            authLogin(call, result);
        } else if (call.method.equals("openDetail")) {
            openDetail(call, result);
        } else if (call.method.equals("loginOut")) {
            loginOut(call, result);
        } else if (call.method.equals("launchUrl")) {
            launchUrl(call, result);
        } else {
            result.notImplemented();
        }
    }

    /**
     * 初始化淘宝客
     *
     * @param call
     * @param result
     */
    public void initialSDK(MethodCall call, final Result result) {
        Map<String, Object> params = new HashMap<>();
        params.put("open4GDownload", true);
        AlibcTradeSDK.asyncInit(mAppContext, params, new AlibcTradeInitCallback() {
            @Override
            public void onSuccess() {
                Log.d("substring", "淘宝客初始化成功");

                if (BuildConfig.DEBUG) {
                    //开发阶段打开日志开关，方便排查错误信息
                    AlibcTradeCommon.turnOnDebug();
                    AlibcTradeCommon.openErrorLog();
                    AlibcTradeBiz.turnOnDebug();
                } else {
                    // 默认是关闭的（也支持手动关闭）
                    AlibcTradeCommon.turnOffDebug();
                    AlibcTradeCommon.closeErrorLog();
                    AlibcTradeBiz.turnOffDebug();
                }

                result.success(true);
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("substring", "淘宝客初始化失败" + code + msg);
                result.error(code + "", msg, null);
            }
        });
    }

    public void launchUrl(MethodCall call, final Result result) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(call.argument("url").toString());
        intent.setData(content_url);
//        intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        mActivity.startActivity(intent);
    }

    /**
     * 淘宝客登出
     *
     * @param call
     * @param result
     */
    public void loginOut(MethodCall call, final Result result) {
        AlibcLogin.getInstance().logout(new AlibcLoginCallback() {
            @Override
            public void onSuccess(String s, String s1) {
                result.success(s + s1);
                Log.d("substring", "淘宝注销成功");
            }

            @Override
            public void onFailure(int i, String s) {
                result.error(i + "", s, null);
                Log.d("substring", "淘宝注销失败");
            }
        });
    }

    /**
     * 淘宝二次授权
     */
    public void authLogin(final Result result, final MethodCall call) {
        CustomActivity.setCallBack(result, call);
        Intent intent = new Intent(mActivity, CustomActivity.class);
        intent.putExtra("method", "authLogin");
        mActivity.startActivity(intent);
    }

    /**
     * 申请淘宝授权登录
     *
     * @param call
     * @param result
     */
    public void authLogin(final MethodCall call, final Result result) {
        String configType = call.argument("configType");
        if (configType != null) {
            if (configType.equals("2")) {
                authLogin(result, call);
                return;
            }
            AlibcLoginCallback loginCallback = new AlibcLoginCallback() {
                @Override
                public void onSuccess(String uid, String nick) {
                    JSONObject mJSONObject = new JSONObject();
                    mJSONObject.put("status", "");
                    result.success(JSON.toJSONString(mJSONObject));
                }

                @Override
                public void onFailure(int i, String s) {
                    Log.d("substring", "onFailure " + s);
                }
            };
            if (AlibcLogin.getInstance().isLogin()) {
                AlibcLogin.getInstance().init(loginCallback);
            } else {
                AlibcLogin.getInstance().showLogin(loginCallback);
            }
        }
    }

//    /**
//     * 开启淘宝商品对应页
//     */
//    public synchronized void openDetail(final MethodCall call, final MethodChannel.Result result) {
//        CustomActivity.setCallBack(result, call);
//        Intent intent = new Intent(mActivity, CustomActivity.class);
//        intent.putExtra("method", "openDetail");
//        mActivity.startActivity(intent);
//    }

    /**
     * 开启淘宝商品对应页
     *
     * @param call
     * @param result
     */
    public synchronized void openDetail(MethodCall call, MethodChannel.Result result) {
        Log.d("substring", "openDetail");
        AlibcBizParams alibcBizParams = new AlibcBizParams();
        JSONObject object = JSONUtils.parseObject(call.argument("json").toString());

        Log.d("substring", call.argument("json").toString());

        // 其他业务参数
        HashMap<String, String> extMap = new HashMap<>();
        // 设置直播间id（此时不要设置商品id）
        extMap.put("id", object.getString("id"));
        alibcBizParams.setId(object.getString("id"));
        alibcBizParams.setExtParams(extMap);
        AlibcShowParams showParams = new AlibcShowParams();
        showParams.setOpenType(OpenType.Auto);
        showParams.setClientType("taobao");
        showParams.setBackUrl("szmf://");
        AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams(object.getString("pid"));
        alibcTaokeParams.pid = object.getString("pid");
        String url = object.getString("url");
        alibcTaokeParams.materialSourceUrl = url;
        String relationId = object.getString("relationId");
        if (!TextUtils.isEmpty(relationId)) {
            alibcTaokeParams.relationId = relationId;
        }
        Map<String, String> trackParams = new HashMap<>(16);
        if (!TextUtils.isEmpty(url)) {
            if (!url.contains("http")) {
                url = url.replace("//uland", "http://uland");
            }
            showParams.setDegradeType(AlibcDegradeType.H5);
            showParams.setDegradeUrl(url);
            AlibcTrade.openByUrl(mActivity, url, showParams, alibcTaokeParams, trackParams, new AlibcTradeCallback() {
                @Override
                public void onSuccess(int i) {
                    Log.d("substring", "open success: code = " + i);
                }

                @Override
                public void onFailure(int i, String s) {
                    Log.d("substring", "open fail: code = " + i + ", msg = " + s);
                }
            });
        } else {
            String codeDetail = "suite://bc.suite.basic/bc.template.detail";
            AlibcTrade.openByCode(mActivity, codeDetail, alibcBizParams, showParams,
                    alibcTaokeParams, trackParams, new AlibcTradeCallback() {
                        @Override
                        public void onSuccess(int i) {
                            Log.d("substring", "open success: code = " + i);
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Log.d("substring", "open fail: code = " + i + ", msg = " + s);
                        }
                    });
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        mActivity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }
}
